#include <SFML/Graphics.hpp>
#include <Box2D/Box2D.h>
#include <cstring>
using namespace sf;

const float SCALE = 30.f;
const float DEG = 57.29577f;

void setWall(b2World& World, int x, int y, int w, int h) {
    b2PolygonShape gr;
    gr.SetAsBox(w / SCALE, h / SCALE);

    b2BodyDef bdef;
    bdef.position.Set(x / SCALE, y / SCALE);

    b2Body* b_ground = World.CreateBody(&bdef);
    b_ground->CreateFixture(&gr, 1);
}

int main() {
    b2Vec2 Gravity(0.f, 9.8f);
    b2World World(Gravity);

    // 创建墙壁
    setWall(World, 400, 520, 2000, 10);
    setWall(World, 400, 450, 10, 170);
    setWall(World, 0, 0, 10, 2000);
    setWall(World, 800, 0, 10, 2000);

    // 窗口和其他初始化代码...
    RenderWindow window(VideoMode(800, 600), "Volleyball Game!");
    window.setFramerateLimit(60);
    window.setSize(Vector2u(800 * 0.8, 600 * 0.8));

    sf::Texture t1, t2, t3;
    t1.loadFromFile("images/background.png");
    t2.loadFromFile("images/ball.png");
    t3.loadFromFile("images/blobby.png");
    t1.setSmooth(true);
    t2.setSmooth(true);
    t3.setSmooth(true);

    sf::Sprite sBackground(t1), sBall(t2), sPlayer(t3);
    sPlayer.setOrigin(75.f / 2.f, 90.f / 2.f);
    sBall.setOrigin(32.f, 32.f);



    while (window.isOpen()) {
        sf::Event e;
        while (window.pollEvent(e)) {
            if (e.type == sf::Event::Closed)
                window.close();
        }

        // 物理世界模拟
        World.Step(1 / 60.f, 8, 3);


        // 绘制代码...
        for (b2Body* it = World.GetBodyList(); it != nullptr; it = it->GetNext()) {
            b2Vec2 pos = it->GetPosition();
            float angle = it->GetAngle();
            void* userDataPtr = &it->GetUserData();
            if (userDataPtr != nullptr) {
                const char* userData = static_cast<const char*>(userDataPtr);

                if (std::strcmp(userData, "player1") == 0) {
                    // 玩家1的绘制
                    sPlayer.setPosition(pos.x * SCALE, pos.y * SCALE);
                    sPlayer.setRotation(angle * DEG);
                    sPlayer.setColor(sf::Color::Red);
                    window.draw(sPlayer);
                }

                if (std::strcmp(userData, "player2") == 0) {
                    // 玩家2的绘制
                    sPlayer.setPosition(pos.x * SCALE, pos.y * SCALE);
                    sPlayer.setRotation(angle * DEG);
                    sPlayer.setColor(sf::Color::Green);
                    window.draw(sPlayer);
                }

                if (std::strcmp(userData, "ball") == 0) {
                    // 球的绘制
                    sBall.setPosition(pos.x * SCALE, pos.y * SCALE);
                    sBall.setRotation(angle * DEG);
                    window.draw(sBall);
                }
            }
        }

        window.display();

    }

    return 0;
}
